# Create your views here.


import json
from django.contrib.auth import login, logout
from django.contrib.auth.hashers import make_password
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.shortcuts import render
from django.urls import reverse
from django.views import View
from user.forms import RegisterForm, LoginForm, RetrievePasswordForm
from user.models import User
from utils.res_code.status_json import status_json
from utils.res_code.status_code import Code, error_map
import logging

log_user = logging.getLogger('user')


class RegisterView(View):
    """
    用户提交注册的类视图
    """

    def get(self, request):
        return render(request, 'user/register.html')

    def post(self, request):
        json_data = request.body
        if not json_data:
            return status_json(no=Code.PARAMERR, msg=error_map[Code.PARAMERR])
        json_dict = json.loads(json_data.decode('utf-8'))
        # print(json_dict)
        # 将ajax提交的json数据转化为dict数据
        form = RegisterForm(json_dict)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            tel = form.cleaned_data.get('tel')
            user = User.objects.create_user(username=username, password=password, mobile=tel)
            # 创建用户
            log_user.info('Register:用户<{}:{}>注册成功'.format(tel, username))
            return status_json(msg="恭喜你注册成功，即将跳转至登录页面")
        else:
            log_user.info(
                'Register:用户<{}:{}>注册失败，Reason<{}>'.format(json_dict['tel'], json_dict['username'], form.get_error))
            return status_json(no=Code.PARAMERR, msg=form.get_error)


class LoginView(View):
    """
    用于用户登录的类视图
    """

    def get(self, request):
        return render(request, 'user/login.html')

    def post(self, request):
        json_data = request.body
        if not json_data:
            return status_json(no=Code.PARAMERR, msg=error_map[Code.PARAMERR])
        json_dict = json.loads(json_data.decode('utf-8'))
        # print(json_dict)
        # 将ajax提交的json数据转化为dict数据
        form = LoginForm(json_dict)
        if form.is_valid():
            user = form.user
            rem_status = form.cleaned_data.get('remember')
            # rem_status为是否记住密码
            if rem_status:
                request.session.set_expiry(7 * 24 * 60 * 60)
            else:
                request.session.set_expiry(0)
            login(request, user)
            log_user.info('Login:用户<{}:{}>登录成功'.format(user.username,user.mobile))
            return status_json(msg="登录成功，即将跳转到主页")
        else:
            log_user.info('Login:用户{}登录失败,Reason:<{}>'.format(json_dict['account'],form.get_error))
            return status_json(no=Code.PARAMERR, msg=form.get_error)


class LogoutView(View):
    """
    用于用户退出账号时的类视图,logout后直接跳转到登录页
    """

    def get(self, request):
        log_user.info('Logout:用户<{}:{}>退出登录'.format(request.user.username,request.user.mobile))
        logout(request)
        return redirect(reverse('user:login'))


class RetrievePasswordView(View):
    """
    用于用户找回密码的类视图
    """

    def get(self, request):
        return render(request, 'user/retrieve_password.html')

    def post(self,request):
        json_data=request.body
        json_dict=json.loads(json_data.decode('utf8'))
        if not json_dict:
            return status_json(no=Code.PARAMERR, msg=error_map[Code.PARAMERR])
        form=RetrievePasswordForm(json_dict)
        if form.is_valid():
            user=form.user
            password=form.cleaned_data.get('password')
            user.update(password=make_password(password))
            log_user.info("Retrieve Password:密码重置成功{}".format(form.cleaned_data.get('tel')))
            return status_json(msg="密码重置成功")
        else:
            log_user.info("Retrieve Password:密码重置失败{}，Reason{}".format(json_dict['tel'],form.get_error))
            return status_json(no=Code.PARAMERR,msg=form.get_error)

